//
//  WaterRecordView.m
//  IphoneMapSdkDemo
//
//  Created by huck on 2017/5/22.
//  Copyright © 2017年 Baidu. All rights reserved.
//

#import "WaterRecordView.h"
#import "AppUtils.h"
#import "HomeManager.h"
#import "MJRefreshFooterView.h"
#import "WaterRecordTableViewCell.h"
#import "SuperviseDetailViewController.h"

static NSString* s_waterRecoardListCellIdentifier = @"WaterRecoardListCellIdentifier";

@interface WaterRecordView ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDelegate>

@property (nonatomic, retain) MJRefreshFooterView *refreshFooterView;
@property (nonatomic) NSInteger pageNO;//分页
@property (nonatomic,strong) NSDate *currentDate;

@property (nonatomic) BOOL hasLoad;

@property (nonatomic, strong) UIView *veilView;
@property (nonatomic, strong) UIView *pickerView;
@property (nonatomic, strong) UIDatePicker *dateView;


@end

@implementation WaterRecordView

+ (instancetype)initViewWithFrameView:(UIView *)view
{
    if (nil == view) {
        return nil;
    }
    WaterRecordView *infoView = [[[NSBundle mainBundle] loadNibNamed:@"WaterRecordView" owner:nil options:nil] firstObject];
    [infoView setFrame:CGRectMake(0, 0, view.width, view.height)];
    [view addSubview:infoView];
    return infoView;
}

-(void)awakeFromNib
{
    [super awakeFromNib];
    [self initSubview];
}

- (void)dealloc
{
    [_refreshFooterView free];
}

-(void)initSubview
{
    _timeLabel.layer.borderColor = [UIColor colorWithString:COLOR_DBD9DE].CGColor;
    _timeLabel.layer.borderWidth = 0.5;
    
    [_searchListTableView registerNib:[UINib nibWithNibName:@"WaterRecordTableViewCell" bundle:nil] forCellReuseIdentifier:s_waterRecoardListCellIdentifier];
    __weak id weakSelf = self;
    _refreshFooterView = [MJRefreshFooterView footer];
    _refreshFooterView.scrollView = _searchListTableView;
    _refreshFooterView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView){
        [weakSelf pullUpRefresh];
    };
    _addBtn.hidden = ![LOGIN_USER canSuperView];
    [self initDatePickerView];
    [self updateTimeInfo];
}

//******************日期选择界面**************[start]********;
-(void)initDatePickerView
{
    _veilView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, CONTENT_HEIGHT-35)];
    _veilView.hidden = YES;
    _veilView.backgroundColor = [UIColor blackColor];
    _veilView.alpha = 0.4;
    _veilView.userInteractionEnabled = YES;
    [_veilView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignResponder)]];
    [self addSubview:_veilView];
    
    _pickerView = [[UIView alloc] initWithFrame:CGRectMake(0, CONTENT_HEIGHT-35, SCREEN_WIDTH, 195)];
    _pickerView.hidden = YES;
    _dateView = [[UIDatePicker alloc] init];
    _dateView.frame = CGRectMake(0, 45, _pickerView.width,150);
    [_dateView addTarget:self action:@selector(dateChange:)forControlEvents:UIControlEventValueChanged];
    _dateView.backgroundColor = [UIColor whiteColor];
    _dateView.tintColor = [UIColor colorWithString:COLOR_494B55];
    _dateView.datePickerMode = UIDatePickerModeDate;
    _dateView.minimumDate = [DateUtil getDateByForamt1:@"1910-01-01 00:00:00"];
    _dateView.maximumDate = [NSDate date];
    [_pickerView addSubview:_dateView];
    
    UIView *textView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _pickerView.width, 45)];
    textView.backgroundColor = [UIColor colorWithRed:247/255.0 green:247/255.0 blue:248/255.0 alpha:1];
    UILabel *textLabel = [[UILabel alloc] init];
    textLabel.text = @"选择日期";
    textLabel.textColor= [UIColor colorWithString:COLOR_494B55];
    textLabel.font = [UIFont systemFontOfSize:16];
    textLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [textView addSubview:textLabel];
    
    UIButton *sure = [[UIButton alloc] initWithFrame:CGRectMake(textView.width-60, 0, 60, textView.height)];
    [sure setTitle:@"确定" forState:UIControlStateNormal];
    sure.titleLabel.font = [UIFont systemFontOfSize:16];
    [sure setTitleColor:[UIColor colorWithString:COLOR_17A4FF] forState:UIControlStateNormal];
    [sure addTarget:self action:@selector(datePickSelect) forControlEvents:UIControlEventTouchUpInside];
    [textView addSubview:sure];

    [_pickerView addSubview:textView];
    [self addSubview:_pickerView];
    NSLayoutConstraint *horizontalCenter = [NSLayoutConstraint constraintWithItem:textLabel attribute:NSLayoutAttributeCenterX  relatedBy:NSLayoutRelationEqual toItem:textView attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f];
    NSLayoutConstraint * verticalCenter = [NSLayoutConstraint constraintWithItem:textLabel attribute:NSLayoutAttributeCenterY  relatedBy:NSLayoutRelationEqual toItem:textView attribute:NSLayoutAttributeCenterY multiplier:1.0f constant:0.0f];
    [textView addConstraints:@[horizontalCenter,verticalCenter]];
}
// 时间改变的监听方法
- (void)dateChange:(UIDatePicker *)date{}

- (void)datePickSelect
{
    _currentDate = _dateView.date;
    [self resignResponder];
    [self updateTimeInfo];
    [self initData];
}

// 点击取消时间选择页面
- (void)resignResponder
{
    [UIView animateWithDuration:0.5 animations:^{
        _pickerView.frame = CGRectMake(0, CONTENT_HEIGHT-35, SCREEN_WIDTH, 195);
    } completion:^(BOOL finished) {
        _pickerView.hidden = YES;
        _veilView.hidden = YES;
    }];
}
//******************日期选择界面**************[END]********;


-(void)updateTimeInfo
{
    if(_currentDate == nil){
        _timeLabel.text =  [DateUtil toSimpleString3:[NSDate date]];
    }else{
        _timeLabel.text = [DateUtil toSimpleString3:_currentDate];
    }
}

- (void)initData
{
    _pageNO = 1;
    _refreshFooterView.stopRefresh = NO;
    [_refreshFooterView setStopRefresh:NO];
    [self requestData:YES showLoading:YES];
    [_searchListTableView setContentOffset:CGPointMake(0, 0)];
}

- (void)requestData:(BOOL)reset showLoading:(BOOL)showLoading
{
    NSString *dateTime = nil;
    if(_currentDate != nil){
        dateTime = [DateUtil toSimpleString:_currentDate];
    }
    //获取一连串参数
    if (showLoading) {
        [Toast loading];
    }
    [[HomeManager sharedInstance] requestSearchWaterRecodeList:dateTime waterId:_waterId page:_pageNO reset:reset complete:^(BOOL success, BOOL hasMore) {
        _hasLoad = YES;
        
        if (_refreshFooterView) {
            [_refreshFooterView endRefreshing];
            [_refreshFooterView setStopRefresh:!hasMore];
        }
        if (showLoading) {
            [Toast loaded];
        }
        if (!reset) {
            [_refreshFooterView endRefreshing];
        }
        if(hasMore){
            _pageNO++;
        }
        [_searchListTableView reloadData];
    }];
}

//上拉刷新
- (void)pullUpRefresh
{
    if ([AppUtils hasConnected:YES]) {
        [self requestData:NO showLoading:NO];
    }
    else {
        [_refreshFooterView endRefreshing];
    }
}

- (IBAction)selectBtnClick:(UIButton *)sender
{
    _veilView.hidden = NO;
    _pickerView.hidden = NO;
    [UIView animateWithDuration:0.5 animations:^{
        _pickerView.frame = CGRectMake(0, self.height - 195, self.width, 195);
    } completion:^(BOOL finished) {
        NSDate *d = _currentDate;
        if(_currentDate == nil){
            d = [NSDate date];
        }
        [_dateView setDate:d animated:NO];
    }];
}

- (IBAction)searchBtnClick:(UIButton *)sender
{
    [self initData];
}

- (IBAction)addBtnClick:(UIButton *)sender
{
    SuperviseDetailViewController *controller= [[SuperviseDetailViewController alloc] init];
    controller.waterId = _waterId;
    controller.recordId = nil;
    controller.waterName = [HomeManager sharedInstance].waterDetailInfo.waterName;
    [[AppUtils getNavigationController] pushViewController:controller animated:YES];
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 滚动到底部，自动加载
    if([AppUtils isScrollToBottom:scrollView] && ![_refreshFooterView isRefreshing] && !_refreshFooterView.stopRefresh) {
        [_refreshFooterView beginRefreshing];
    }
}

#pragma mark UITableDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger count =  [HomeManager sharedInstance].waterRecordList.count;
    _emptyView.hidden = count>0 || !_hasLoad;
    return [HomeManager sharedInstance].waterRecordList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    WaterRecordTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:s_waterRecoardListCellIdentifier];
    if (nil == cell) {
        return nil;
    }
    
    WaterRecodeItemData *data = [[HomeManager sharedInstance].waterRecordList objectAtIndex:indexPath.row];
    
    [cell setInfo:data index:indexPath.row];
    return cell;
}

@end
